<?php

require_once APP . 'controllers/accounts_controller.php';

class OpenidController extends AccountsController {

  function login() {
    $return_to = 'http://' . $_SERVER['SERVER_NAME'] . $this->here;
    if (!empty($this->data) && $this->data['OpenidUrl']['openid']) {
      try {
  $this->OpenidAuth->authenticate($this->data['OpenidUrl']['openid'], $return_to, 'http://'.$_SERVER['SERVER_NAME'], /*required*/array('email', 'fullname'));
        error_log("1-".json_encode($this->data));
      } 
      catch (InvalidArgumentException $e) {
        $this->setError('Ungültige OpenID', array('controller' => 'users', 'action' => 'login'));
      } 
      catch (Exception $e) {
        $this->setError($e->getMessage(), array('controller' => 'users', 'action' => 'login'));
      }
    } 
    else
    if ($this->OpenidAuth->isOpenIDResponse()) {
      $response = $this->OpenidAuth->getResponse($return_to);
 
      if ($response->status == Auth_OpenID_CANCEL) {
        $this->setError('Verifizierung abgebrochen', array('controller' => 'users', 'action' => 'login'));
      } 
      else
      if ($response->status == Auth_OpenID_FAILURE) {
        $this->setError('Die Verifizierung der OpenID schlug fehl: ' . $response->message, 
          array('controller' => 'users', 'action' => 'login'));
      } 
      else
      if ($response->status == Auth_OpenID_SUCCESS) {
        $identity_url = $response->identity_url;

        $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
        $sreg = $sreg_resp->contents();

        $prev_account = $this->Auth->user();
        if ($prev_account) {
          $user_id = $this->User->user_id($prev_account);
          $this->Auth->logout();
        }

        $fullname = @$sreg['fullname'];
        $email = @$sreg['email'];
        
        /*
         * 3 cases:
         * - user is logged in by some other means
         * - user is not logged in but we find her email address in a user
         * - user is not logged in, we create a new user with her email address
         */     
        $account = $this->OpenidAccount->find('first', array(
          'conditions' => array('OpenidAccount.identity_url' => $identity_url),
          'fields' => array('OpenidAccount.id', 'OpenidAccount.user_id', 'OpenidAccount.identity_url')));
         
        if (!$account) {
          // New account. Create it

          // First, check if we can identify the user from (1) this or (2) the previous account
          if (!isset($user_id) && $email) {
            $user_id = $this->User->field('user_id', array('User.email' => $email));
          }
          
          if (isset($user_id) && $user_id) {
            // We found a user. Check if we can enhance it with fullname and/or email
            $user = $this->User->find('first', array('conditions' => array('id' => $user_id)));
            $data = array();
            if ($fullname && !$user['User']['name']) {
              $data['name'] = $fullname;
            }
            if ($email && !$user['User']['email']) {
              $data['email'] = $email;
            }
            if ($data) {
              $this->User->set('id', $user_id);
              $this->User->save($data);
            }
          }
          else {
            // No user found. create a new one for this account
            $data = array();
            if ($fullname) {
              $data['name'] = $fullname;
            }
            if ($email) {
              $data['email'] = $email;
            }
            $this->User->save($data);
            $user_id = $this->User->getInsertID();
          }

          // We now are sure to have a user id and can create the account
          $account = $this->OpenidAccount->save(array(
            'user_id' => $user_id,
            'identity_url' => $identity_url));
        }
          
        // Either way, we should now have an $account

        $this->Session->write('auth_component', 'OpenidAuth');
        $this->Session->write('user', $account);        

        if ($account) {
          error_log("4-" . json_encode($account));
          $this->setSuccess('Du bist erfolgreich per OpenID angemeldet.', 
            array('controller' => 'users', 'action' => 'view', $account['OpenidAccount']['user_id']));
        }
        else {
          $this->setError('Die Anmeldung per OpenID schlug fehl.', 
            array('controller' => 'users', 'action' => 'login'));
        }
      }
      else {
        error_log("2-" . json_encode($response->status));
      }
    }
    else {
      error_log("3-" . json_encode($this->OpenidAuth));
      $this->setSuccess('Alles klar', array('controller' => 'points', 'action' => 'home')); 
    }
  }

  function delete($id) {
    parent::delete($id, 'Openid');
  }
}
